package com.itheima.reggie.controller;

import cn.hutool.core.util.ObjectUtil;

import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.dto.PageDto;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.vo.R;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 员工相关接口
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        R loginR = employeeService.login(employee);
        if (ObjectUtil.isNotNull(loginR.getData())) session.setAttribute("employee", loginR.getData());
        return loginR;
    }


    /**
     * 登出
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        //清理Session中保存的当前登录员工的id
        session.invalidate();
        return R.success("退出成功");
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R addEmp(@RequestBody Employee employee, HttpSession session) {
        /*//从session中获取登录的用户名
        Employee empId = (Employee) session.getAttribute("employee");
        employee.setUpdateUser(empId.getId());//修改人
        employee.setCreateUser(empId.getId());//创建人*/

        //调用service做检验并保存到数据库
        return employeeService.addEmp(employee);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R page(PageDto pageDto) {
        return employeeService.page(pageDto);
    }

    /**
     * 账号状态
     */
    @PutMapping
    public R updateEmp(@RequestBody Employee employee, HttpServletRequest request) {
        //调用service做检验并保存到数据库
        if (request.getHeader("Referer").contains("list.html")){
            //修改状态
            return employeeService.updateEmp(employee,"status");
        }else {
            //修改信息
           return employeeService.updateEmp(employee,"info");
        }
    }

    /**
     * 编辑员工
     */
    @GetMapping("{id}")
    public R findEmpById(@PathVariable("id") Long id) {
        return R.success(employeeService.getById(id));
    }

}
